<?php
    /**
    -------------------------
    GNU GPL COPYRIGHT NOTICES
    -------------------------
    This file is part of FlexicaCMS.

    FlexicaCMS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    FlexicaCMS is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with FlexicaCMS.  If not, see <http://www.gnu.org/licenses/>.*/

    /**
    * $Id$
    *
    * @author FlexicaCMS team <contact@flexicacms.com>
    * @link http://www.flexicacms.com/
    * @copyright Copyright &copy; 2009-2010 Gia Han Online Solutions Ltd.
    * @license http://www.flexicacms.com/license.html
    */
    Yii::import('application.modules.Core.extensions.web.mail.EmailMessage');     
    class ToolsController extends BackOfficeController
    {
        public function actionFileManager() {
            $this->render('fileManager');
        }

        public function actionResetSequences() {
            //SELECT setval('site_id_seq', (SELECT MAX(id) FROM site)+1);
            $tables = Yii::app()->db->getSchema()->getTables();

            $log = '';
            foreach($tables as $table) {
                $name = $table->rawName;
                $primaryKey = $table->primaryKey;
                $seq = $table->sequenceName;

                if (!empty($seq)){
                    Yii::app()->db->createCommand("SELECT setval('{$seq}', (SELECT MAX({$primaryKey}) FROM {$name})+1);")->execute();
                    $log .= "Reset sequence {$seq} for {$name}.{$primaryKey}.<br />";
                }
            }
            $this->renderText($log);
        }

        public function actionRebuildCache()
        {
            // CORE cache which are not using standard Yii implementation for caching, i.e. Parameter cache
            FSM::run('Core.Settings.rebuildCache');

            // Delete Yii's cache
            try{
                Yii::app()->cache->flush();
            }catch(Exception $ex) {
                Yii::log("Error while flushing cache value:\n".$ex->getMessage());
            }

            $this->message = Yii::t('Core','Rebuild cache successfully.');
            $this->redirect(array('/Admin'));
        }
        /**
        * Edit the email template, all email template now has been located in runtime/emails. Please make sure do it.
        * 
        */
        public function actionManageTemplates() {
            $model = new EmailMessage('search');
            //clear defaul value
            $model->unsetAttributes();
            if (isset($_GET['EmailMessage']))
                $model->attributes = $_GET['EmailMessage'];

            $this->render('manageTemplates', array(
            'model' => $model,
            ));
        }

        public function actionUpdateTemplates() {
            $dir = Yii::app()->runtimePath . '/emails';
            $idFile = $this->get('id', 0);

            $model = new EmailMessage;
            $model = $model->findByPk($idFile);
            if (empty($model)) {
                throw new CHttpException(400, Yii::t('Core', 'File ID invalid.'));
            }
            $selectedFile = EmailMessage::convertPath2FileName($model->class_path) . '.php';
            $filepath=$dir . '/' . $selectedFile;
            $paramList = $model->getParameters();

            if (Yii::app()->request->getIsPostRequest()) {
                $content = $this->post('content', '', 'xss,notag');
                if(preg_match_all('/&lt;#(.*?)#&gt;/',$content,$match)){                    
                    foreach($match[0] as $key=>$matchItem){
                        if(strpos($matchItem,'Settings::')){
                            $content=str_replace($matchItem,"<?php echo ".$match[1][$key].";?>",$content);
                        }
                        else{
                            $content=str_replace($matchItem,"<?php echo $".$match[1][$key].";?>",$content);
                        }                        
                    }                   
                } 
                if (!empty($model)) {        
                    $subject=str_replace('<#','{$data["',$_POST['EmailMessage']['subject']);
                    $subject=str_replace('#>','"]}',$subject);        
                    $model->attributes = $_POST['EmailMessage'];
                    $model->template = $content;                    
                    $model->subject=$subject;
                    if($model->save()){
                        if (is_file($filepath)) {
                            file_put_contents($filepath, $content);
                        } else {
                            $f = fopen($filepath, 'w+');
                            if ($f == false) {
                                throw new CHttpException(400, Yii::t('Core', 'Cannot open file template.'));
                            }
                            fwrite($f, $content);
                            fclose($f);
                        }
                    }                        
                }
            }
            else{
                if (is_file($filepath)) {        
                    $content = file_get_contents($filepath);
                } else {
                    $content = null;
                }
                if (is_null($content))
                    $content = $model->template;    

                //set default email address and name if they null
                if(empty($model->sender_email)){
                    if(hasParam("Settings::MAIL_SERDER_ADDRESS")){
                        $model->sender_email=Settings::MAIL_SERDER_ADDRESS;    
                    }                    
                }
                if(empty($model->sender_name)){
                    if(hasParam("Settings::MAIL_SENDER_NAME")){
                        $model->sender_name=Settings::MAIL_SENDER_NAME;
                    }

                }
            }
            $subject=str_replace('{$data["','<#',$model->subject);
            $subject=str_replace('"]}','#>',$subject);
            $model->subject=$subject;
            $this->render('updateTemplates', array(
            'content' => $content,        
            'model' => $model,
            'paramList' => $paramList,
            ));
        }
        public function actionLookupSenderEmail()
        {
            if(Yii::app()->request->isAjaxRequest && isset($_GET['q']))
            {                
                $name = $_GET['q']; 
                $type=$this->get('type','');
                $selectColumn="id";
                if($type=='email')
                {
                    $selectColumn='sender_email';
                }
                elseif($type=='name'){
                    $selectColumn='sender_name';                    
                }
                // this was set with the "max" attribute of the CAutoComplete widget
                $limit = min($_GET['limit'], 50); 
                $criteria = new CDbCriteria;
                $criteria->select=$selectColumn;
                $criteria->condition = $selectColumn." LIKE :sterm";
                $criteria->params = array(":sterm"=>"%$name%");
                $criteria->limit = $limit;
                $criteria->distinct=true;
                $emails = EmailMessage::model()->findAll($criteria);
                $returnVal = '';
                foreach($emails  as $email)
                {
                    $returnVal .= $email->$selectColumn."\n";
                }
                echo $returnVal;
                Yii::app()->end();
            }             
        }
    }
?>